package com.juzi.wopu.web;

import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.juzi.wopu.domain.CanteenMenu;
import com.juzi.wopu.domain.CartPlace;
import com.juzi.wopu.domain.CartShelf;
import com.juzi.wopu.domain.CartShelfResponse;
import com.juzi.wopu.domain.CartSupplier;
import com.juzi.wopu.domain.Employee;
import com.juzi.wopu.domain.SysCode;
import com.juzi.wopu.domain.SysProduct;
import com.juzi.wopu.query.CartShelfQuery;
import com.juzi.wopu.query.PageList;
import com.juzi.wopu.service.ICanteenMenuService;
import com.juzi.wopu.service.ICartPlaceService;
import com.juzi.wopu.service.ICartShelfService;
import com.juzi.wopu.service.ICartSupplierService;
import com.juzi.wopu.service.IImageService;
import com.juzi.wopu.service.ISysCodeService;
import com.juzi.wopu.service.ISysProductService;
import com.juzi.wopu.service.impl.IImageServiceImpl;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.interceptor.annotations.InputConfig;

public class CartShelfAction extends CRUDAaction<CartShelf> {
	
	private static final long serialVersionUID = 1L;

	private ICartShelfService cartShelfService;
	
	private ISysCodeService sysCodeService;
	
	private ICanteenMenuService canteenMenuService;
	
	private ISysProductService sysProductService;
	
	private ICartPlaceService cartPlaceService;
	
	private ICartSupplierService cartSupplierService;
	
	private IImageService imageService=new IImageServiceImpl();

	private CartShelf cartShelf = new CartShelf();
	
	private CartShelfQuery baseQuery = new CartShelfQuery();
	
	private PageList pageList;
	
	private List<CartShelfResponse> data=new ArrayList<>();
	
	private File upload;
	private String contentType;
	private String fileName;
	
	private Long typeCode;
	
	private String type;
	
	public Long getTypeCode() {
		return typeCode;
	}

	public void setTypeCode(Long typeCode) {
		this.typeCode = typeCode;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}
	
	public String getUploadContentType() {
		return contentType;
	}

	public void setUploadContentType(String contentType) {
		this.contentType = contentType;
	}

	public String getUploadFileName() {
		return fileName;
	}

	public void setUploadFileName(String fileName) {
		this.fileName = fileName;
	}
	
	public List<CartShelfResponse> getData() {
		return data;
	}

	public void setData(List<CartShelfResponse> data) {
		this.data = data;
	}

	public void setCartShelfService(ICartShelfService cartShelfService) {
		this.cartShelfService = cartShelfService;
	}
	
	public void setSysCodeService(ISysCodeService sysCodeService) {
		this.sysCodeService = sysCodeService;
	}
	
	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	@Override
	protected void list() {
		if(companyName!=null){
			ActionContext.getContext().getSession().put("companyName", companyName);
		}
		else {
			companyName=(String) ActionContext.getContext().getSession().get("companyName");
		}
		Map<String, SysCode> nameCodeMap=new HashMap<>();
		Map<Long, SysCode> map=new HashMap<>();
		sysCodeService.getSysCodeMap(map, nameCodeMap);//得到sName对应SysCode的map
		Long companyCode=nameCodeMap.get(companyName).getiId();//根据传过来的局点名得到局点的代码，如1902
		baseQuery.setCompanyCode(companyCode);
		Collection<SysCode> list=nameCodeMap.values();//查询出来的所有的SysCode
		
		this.pageList = cartShelfService.findByQuery(baseQuery);
		List<SysCode> allCompanyCode=new ArrayList<>();
		List<SysCode> allSyscode=new ArrayList<>();
		if(list!=null && list.size()>0){
			for(SysCode sysCode:list){
				if(sysCode.getiType()!=null && sysCode.getiType()==4L){
					allCompanyCode.add(sysCode);
			    }
				if(sysCode.getiType()!=null && sysCode.getiType()==1L
						&& sysCode.getiParentId()!=null && sysCode.getiParentId()==99L){
					allSyscode.add(sysCode);
			    }
			}
		}
		
		if(pageList!=null && pageList.getRows()!=null && pageList.getRows().size()>0){
			@SuppressWarnings("unchecked")
			List<Object> rows=pageList.getRows();
			for(Object pro:rows){
				((CartShelf)pro).setType(((CartShelf)pro).getSysCode().getiId()+" - "+((CartShelf)pro).getiTypeSub());
				CartShelfResponse response=new CartShelfResponse((CartShelf)pro);
				String imgPath=imageService.downloadSmallImg(((CartShelf)pro).getsProductImage());
				response.setSmallImgPath(imgPath);
				response.setsCompany(map.get(response.getiCompany()).getsName());
				Long goodsId=((CartShelf)pro).getiGoodsId();
				if(((CartShelf)pro).getSysCode()!=null){
					if(((CartShelf)pro).getSysCode().getiId()==910L){
						CanteenMenu canteenMenu=canteenMenuService.findById(goodsId);
						if(canteenMenu==null){
							response.setiTypeSub(-1L);
							response.setSubTypeName("");
						}else {
							response.setiTypeSub(canteenMenu.getSysCode().getiId());
							SysCode sysCode=map.get(response.getiTypeSub());
							if(sysCode==null){
								response.setiTypeSub(-1L);
								response.setSubTypeName("");
							}else {
								response.setSubTypeName(sysCode.getSName());
							}
							
						}
						
					}else {
						SysProduct sysProduct=sysProductService.findById(goodsId);
						if(sysProduct==null){
							response.setiTypeSub(-1L);
							response.setSubTypeName("");
						}else {
							response.setiTypeSub(sysProduct.getiTypeSub());
							SysCode sysCode=map.get(response.getiTypeSub());
							if(sysCode==null){
								response.setiTypeSub(-1L);
								response.setSubTypeName("");
							}else {
								response.setSubTypeName(sysCode.getSName());
							}
//							response.setSubTypeName(map.get(response.getiTypeSub()).getSName());
						}
					}
				}
				
				data.add(response);
			}
		}
		putContext("allCompanyCode",allCompanyCode);
		putContext("allSyscode",allSyscode);
	}

	/**
	 * 上架和下架
	 * @return
	 */
	public String upDownStatus(){
		cartShelfService.updateStatus(id);
		return RELOAD;
	}
	
	@Override
	public String input() throws Exception {
		List<SysCode> list=sysCodeService.getAll();
		
//		List<Type> allType=new ArrayList<>();
//		if(list!=null && list.size()>0){
//			for(SysCode code:list){
//				if(code.getiParentId()!=null && code.getiParentId()==99L){
//					for(SysCode code1:list){
//						if(code1.getiParentId()!=null && 
//								code1.getiParentId().intValue()==code.getIId().intValue()){
//							Type type=new Type();
//							type.setTypeCode(code.getiId());
//							type.setTypeName(code.getsName());
//							type.setSubTypeCode(code1.getiId());
//							type.setSubTypeName(code1.getsName());
//							type.setTotalTypeCode(code.getiId()+" - "+code1.getiId());
//							type.setTotalTypeName(code.getsName()+" - "+code1.getsName());
//							allType.add(type);
//						}
//					}
//				}
//			}
//		}
//		putContext("allType", allType);
		
		
		companyName=(String) ActionContext.getContext().getSession().get("companyName");
		long company=-1L;
		for(SysCode sysCode:list){
			if(sysCode.getsName().equals(companyName)){
				company=sysCode.getiId();
				break;
			}
		}
		
		List<CartPlace> cartPlaceList=cartPlaceService.findByCompany(company);
		
		List<SysCode> allCompanyCode=new ArrayList<>();
		List<SysCode> allSyscode=new ArrayList<>();
		if(list!=null && list.size()>0){
			for(SysCode sysCode:list){
				if(sysCode.getiType()!=null && sysCode.getiType()==4L){
					allCompanyCode.add(sysCode);
			    }
				if(sysCode.getiType()!=null && sysCode.getiType()==1L
						&& sysCode.getiParentId()!=null && sysCode.getiParentId()==99L){
					allSyscode.add(sysCode);
			    }
			}
		}
		putContext("allCompanyCode",allCompanyCode);
		putContext("allSyscode",allSyscode);
		putContext("cartPlaceList",cartPlaceList);
		
		List<SysCode> subTypeCode=new ArrayList<>();
		for(int i=0;i<allSyscode.size();i++){
			long parentId=allSyscode.get(i).getIId();
			for(SysCode sCode:list){
				if(sCode.getiParentId()!=null && sCode.getiParentId()==parentId){
					subTypeCode.add(sCode);
				}
			}
		}
		
		putContext("subTypeCode",subTypeCode);
		return INPUT;
	}
	

	public String getSubType(){
		return "test";
	}
	
	public void validateSave() {
		if (StringUtils.isBlank(cartShelf.getsProductName())) {
			addFieldError("name", "名称不能为空");
		}
	}

	@Override
    @InputConfig(methodName="input")
	public String save() throws Exception {
//		if(type==null || type.equals("-1")){
//			if(cartShelf.getSysCode()==null){
//				cartShelf.setSysCode(new SysCode());
//			}
//			cartShelf.getSysCode().setiId(-1L);
//			cartShelf.setiTypeSub(-1L);
//		}else {
//			String[] types=type.split(" - ");
//			if(cartShelf.getSysCode()==null){
//				cartShelf.setSysCode(new SysCode());
//			}
//			cartShelf.getSysCode().setiId(Long.parseLong(types[0]));
//			cartShelf.setiTypeSub(Long.parseLong(types[1]));
//		}
		
		
		Employee loginUser=getLoginUser();
		cartShelf.setiUpdateUser(loginUser.getId());
		
		Map<String, SysCode> nameCodeMap=new HashMap<>();
		sysCodeService.getSysCodeMap(null, nameCodeMap);//得到sName对应SysCode的map
		Map<Long, CartSupplier> codeSupplierMap=new HashMap<>();
		cartSupplierService.getCartSupplierMap(codeSupplierMap,null);
		Map<Long, CartPlace> codePlaceMap=new HashMap<>();
		cartPlaceService.getCartPlaceMap(codePlaceMap,null);
		
		if(id==null){//添加
			if(upload!=null){
				String imgPath=imageService.upload(upload, cartShelf.getSysCode().getiId()+"");
				cartShelf.setsProductImage(imgPath);
			}else {
				cartShelf.setsProductImage("");
			}
			System.out.println(cartShelf.getiCount());
			companyName=(String) ActionContext.getContext().getSession().get("companyName");
			baseQuery.setCurrentPage(Integer.MAX_VALUE);
			
			cartShelf.setsCompany(companyName);
			cartShelf.setiCompany(nameCodeMap.get(companyName).getIId());
			
			cartShelf.setiStatus(0L);
			cartShelf.setiSold(0L);
			cartShelf.setiDeliver(0L);
			cartShelf.setDtInsert(new Date());
			cartShelf.setDtUpdate(new Date());
			
			cartShelf.setsPlaceName(codePlaceMap.get(cartShelf.getiPlaceId()).getsName());
			cartShelf.setiSupplierId(codePlaceMap.get(cartShelf.getiPlaceId()).getiSupplier());
			cartShelf.setsSupplierName(codeSupplierMap.get(cartShelf.getiSupplierId()).getSName());
			
			cartShelf.setiInsertUser(loginUser.getId());
			if(cartShelf.getSysCode().getiId()==910L){//净菜
				CanteenMenu canteenMenu=new CanteenMenu();
				canteenMenu.setsName(cartShelf.getsProductName());
				canteenMenu.setsDes("");
				canteenMenu.setsMain("");
				canteenMenu.setsAdjuvant("");
				canteenMenu.setsSeasoning("");
				canteenMenu.setsCooking("");
				canteenMenu.setsImgPath(cartShelf.getsProductImage());
				canteenMenu.setsImgDeal(cartShelf.getsProductImage());
				canteenMenu.setsImgOld(cartShelf.getsProductImage());
				canteenMenu.setdPrice(cartShelf.getDPrice());
				SysCode sCode=new SysCode();
				sCode.setIId(cartShelf.getiTypeSub());
				canteenMenu.setSysCode(sCode);
				
				canteenMenuService.save(canteenMenu);
				CanteenMenu cm=canteenMenuService.findLast();
				long iGoodsId=cm.getIId();
				cartShelf.setiGoodsId(iGoodsId);
				
			}else {
				SysProduct product=new SysProduct();
				product.setsName(cartShelf.getsProductName());
				product.setiTypeSub(cartShelf.getiTypeSub());
				product.setsImgPath(cartShelf.getsProductImage());
				product.setdPriceOri(cartShelf.getDPrice());
				product.setDtInsert(new Date());
				product.setsDes("");
				product.setSysCode(cartShelf.getSysCode());
				sysProductService.save(product);
				
				SysProduct s=sysProductService.findLast();
				long iGoodsId=s.getIId();
				cartShelf.setiGoodsId(iGoodsId);
			}
			cartShelfService.save(cartShelf);
		}else {
			//更新
			if(upload!=null){
				String imgPath=imageService.upload(upload, cartShelf.getSysCode().getiId()+"");
				cartShelf.setsProductImage(imgPath);
			}
			
			cartShelf.setDtUpdate(new Date());
			cartShelf.setsPlaceName(codePlaceMap.get(cartShelf.getiPlaceId()).getsName());
			cartShelf.setiSupplierId(codePlaceMap.get(cartShelf.getiPlaceId()).getiSupplier());
			cartShelf.setsSupplierName(codeSupplierMap.get(cartShelf.getiSupplierId()).getSName());
			
			if(cartShelf.getSysCode().getiId()==910L){//净菜
				CanteenMenu canteenMenu=new CanteenMenu();
				System.out.println(cartShelf.getDtStart());
				System.out.println(cartShelf.getDtEnd());
				System.out.println(cartShelf.getiCount());
				canteenMenu.setiId(cartShelf.getiGoodsId());
				canteenMenu.setsName(cartShelf.getsProductName());
				canteenMenu.setsMain("");
				canteenMenu.setsImgPath(cartShelf.getsProductImage());
				canteenMenu.setsImgDeal(cartShelf.getsProductImage());
				canteenMenu.setsImgOld(cartShelf.getsProductImage());
				canteenMenu.setdPrice(cartShelf.getDPrice());
				SysCode sCode=new SysCode();
				sCode.setIId(cartShelf.getiTypeSub());
				canteenMenu.setSysCode(sCode);
				
				if(cartShelf.getiGoodsId()==null){
					canteenMenuService.save(canteenMenu);
					CanteenMenu cm=canteenMenuService.findLast();
					long iGoodsId=cm.getIId();
					cartShelf.setiGoodsId(iGoodsId);
				}
				else {
					canteenMenuService.update(canteenMenu);
				}
			}else {
				SysProduct product=new SysProduct();
				product.setiId(cartShelf.getiGoodsId());
				product.setsName(cartShelf.getsProductName());
				product.setiTypeSub(cartShelf.getiTypeSub());
				product.setsImgPath(cartShelf.getsProductImage());
				product.setdPriceOri(cartShelf.getDPrice());
				product.setDtInsert(new Date());
				product.setsDes("");
				product.setSysCode(cartShelf.getSysCode());
				
				if(cartShelf.getiGoodsId()==null){
					sysProductService.save(product);
					SysProduct s=sysProductService.findLast();
					long iGoodsId=s.getIId();
					cartShelf.setiGoodsId(iGoodsId);
				}else {
					sysProductService.update(product);
				}
			}
			cartShelfService.update(cartShelf);
		}
		return RELOAD;
	}


	@Override
	public String delete() throws Exception {
		HttpServletResponse response=ServletActionContext.getResponse();
		response.setContentType("text/json;charset=UTF-8");
		PrintWriter out = response.getWriter();
		try {
			if (id != null) {
				cartShelfService.delete(id);
				out.print("{\"success\":true,\"msg\":\"删除成功\"}");
			}else{
				out.print("{\"success\":false,\"msg\":\"没有删除成功\"}");
			}
		} catch (Exception e) {
			e.printStackTrace();
			out.print("{\"success\":false,\"msg\":\"异常信息:"+e.getMessage()+"\"}");
		}
		return null;
	}

	@Override
	public void prepareInput() throws Exception {
		if (id != null) {// 最主要做回显
			cartShelf = cartShelfService.get(id);// 变成栈顶对象
		}
	}

	@Override
	public void prepareSave() throws Exception {
		if (id == null) {
			cartShelf = new CartShelf();
		} else {
			cartShelf = cartShelfService.get(id);
			cartShelf.setSysCode(null);
		}
	}

	@Override
	public CartShelf getModel() {
		return cartShelf;
	}

	public PageList getPageList() {
		return pageList;
	}

	public CartShelfQuery getBaseQuery() {
		return baseQuery;
	}

	public void setBaseQuery(CartShelfQuery baseQuery) {
		this.baseQuery = baseQuery;
	}

	public ICanteenMenuService getCanteenMenuService() {
		return canteenMenuService;
	}

	public void setCanteenMenuService(ICanteenMenuService canteenMenuService) {
		this.canteenMenuService = canteenMenuService;
	}

	public ISysProductService getSysProductService() {
		return sysProductService;
	}

	public void setSysProductService(ISysProductService sysProductService) {
		this.sysProductService = sysProductService;
	}

	public ICartPlaceService getCartPlaceService() {
		return cartPlaceService;
	}

	public void setCartPlaceService(ICartPlaceService cartPlaceService) {
		this.cartPlaceService = cartPlaceService;
	}

	public IImageService getImageService() {
		return imageService;
	}

	public void setImageService(IImageService imageService) {
		this.imageService = imageService;
	}

	public ICartShelfService getCartShelfService() {
		return cartShelfService;
	}

	public ISysCodeService getSysCodeService() {
		return sysCodeService;
	}

	public ICartSupplierService getCartSupplierService() {
		return cartSupplierService;
	}

	public void setCartSupplierService(ICartSupplierService cartSupplierService) {
		this.cartSupplierService = cartSupplierService;
	}
}